package com.pansoft.openplanet.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.chat.view.CommonOtherPopWindow;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.MyAirDropActivity;
import com.pansoft.openplanet.bean.AirDropModel;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.TCLoadingDataView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 空投场
 *
 * @author YQS
 */
public class AirDropFragment extends BaseFragment {
    private static final String TAG = "AirDropFragment";
    private OnAirDropFragmentInteractionListener mListener;
    private StubObject stubObject;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private List<AirDropModel.AirportlistBean> mDatas;
    private int page = 1;
    private AirDropRecyclerViewAdapter mAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            stubObject = (StubObject) getArguments().getSerializable("stubObject");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.assets_fragment_air_drop, container, false);
        refreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.list);
        initListener();
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mDatas = new ArrayList<>();
        mAdapter = new AirDropRecyclerViewAdapter(getContext(), mDatas, mListener);
        recyclerView.setAdapter(mAdapter);
        if (getUserVisibleHint()){
            TCLoadingDataView.show(getActivity());
        }
        loadData(page, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public AirDropFragment() {
    }


    private void initListener() {
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page += 1;
                loadData(page, true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (mDatas != null) {
                    mDatas.clear();
                    mAdapter.notifyDataSetChanged();
                    page = 1;
                    loadData(page, false);
                }
            }
        });
    }

    private void loadData(int page, boolean isLoadMore) {
        final HashMap<String, String> map = new HashMap<>();
        map.put("page", page + "");
        map.put("pagesize", "10");
        map.put("userId", EnvironmentVariable.getUserName());

        TCRequestUtil.getCommonRequest(TAG, "aridrop/airportlist", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                TCLoadingDataView.dismiss();
                refreshLayout.finishLoadMore(100);
                refreshLayout.finishRefresh(100);
                try {
                    AirDropModel airDropModel = new Gson().fromJson(response, AirDropModel.class);
                    if (airDropModel == null) {
                        if (getUserVisibleHint()) {
                            ToastUtil.showToast(AppContext.getInstance(), ResStringUtil.getString(R.string.common_text_http_request_fail));
                            return;
                        }
                    }
                    if (airDropModel.getResult().equals("success")) {
                        List<AirDropModel.AirportlistBean> list = airDropModel.getAirportlist();
                        if (list != null) {
                            mDatas.addAll(list);
                            mAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (getUserVisibleHint()) {
                            ToastUtil.showToast(AppContext.getInstance(), ResStringUtil.getString(R.string.common_text_http_request_fail));
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    TCLoadingDataView.dismiss();
                    if (getUserVisibleHint()) {
                        ToastUtil.showToast(AppContext.getInstance(), ResStringUtil.getString(R.string.common_text_http_request_fail));
                    }
                }
            }

            @Override
            public void onFail(String error) {
                TCLoadingDataView.dismiss();

                refreshLayout.finishLoadMore(100);
                refreshLayout.finishRefresh(100);
                if (getUserVisibleHint()) {
                    ToastUtil.showToast(AppContext.getInstance(), ResStringUtil.getString(R.string.common_text_http_request_fail));
                }
            }
        });

    }

    //TODO 处理tabmenu 点击(滚动到顶部)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onSolveEvent(TabMenuClickEvent event) {
        if (getArguments() != null) {
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            if (event.isChildPage(stubObject) && !isHidden()) {
                recyclerView.smoothScrollToPosition(0);
                refreshLayout.autoRefresh();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showPopMenu1(RightTopMenuClickEvent event) {
        StubObject stubObject = event.getStubObject();
        if (stubObject.getString("AndroidShow", "").equals("com.pansoft.openplanet.fragment.AirDropFragment")) {
            final CommonOtherPopWindow popWindow = new CommonOtherPopWindow(getActivity());
            popWindow.addMenuButton(ResStringUtil.getString(R.string.open_planet_my_airdrop), R.drawable.assets_menu_airdrop, true).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyAirDropActivity.start(getActivity());
                    popWindow.dismiss();
                }
            });
            popWindow.showPopupWindow(event.getView());

        }
    }

    public interface OnAirDropFragmentInteractionListener {
        void onListFragmentInteraction(AirDropModel item);
    }
}
